package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.SetmealDao;
import com.itheima.domain.RedisConstant;
import com.itheima.domain.Setmeal;
import com.itheima.result.PageResult;
import com.itheima.service.SetmealService;
import com.itheima.utils.QiniuUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outputpath ;
    //cookie.setMaxAge(60*60*24*30);//有效期30天
    //response.addCookie(cookie);
    ////保存会员信息到Redis中
    //String json = JSON.toJSON(member).toString();
    //jedisPool.getResource().setex(telephone,60*30,json);

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        Integer setmealId = setmeal.getId();
        if (checkgroupIds!=null&&checkgroupIds.length>0){
        setSetmealAndCheckgroup(setmealId,checkgroupIds);
        }
        if (setmeal.getImg()!=null){
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        }
        generateMobileStaticHtml();
    }

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<Setmeal> page=setmealDao.findPage(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public Setmeal findById(Integer id) {
        Setmeal setmeal=setmealDao.findById(id);
        return setmeal;
    }

    @Override
    public List<Integer> findCheckGroupIdsBySetmealId(Integer id) {
       List<Integer> checkgroupIds=setmealDao.findCheckGroupIdsBySetmealId(id);
        return checkgroupIds;
    }

    @Override
    public void edit(Setmeal setmeal, Integer[] checkGroupIds, String setmealUrl) {
        setmealDao.deleteAssociation(setmeal.getId());
        if (checkGroupIds!=null&&checkGroupIds.length>0){
            setSetmealAndCheckgroup(setmeal.getId(),checkGroupIds);
        }
        setmealDao.edit(setmeal);
        if (!"null".equals(setmeal.getImg())){
            if (!"null".equals(setmealUrl)){
                if (!setmeal.getImg().equals(setmealUrl)){
                    jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmealUrl);
                    jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
                }else {
                    jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
                }
            }

        }else {
            if (!"null".equals(setmealUrl)){
                jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmealUrl);
            }
        }
        generateMobileStaticHtml();
    }

    @Override
    public void delete(Setmeal setmeal) {
        System.out.println(setmeal.getId());
        setmealDao.deleteAssociation(setmeal.getId());
        setmealDao.deleteSetmel(setmeal.getId());
        if (setmeal.getImg()!=null){
            jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        }
        //删除静态页面
        File file = new File(outputpath + "/" + "setmeal_detail_" + setmeal.getId() + ".html");
        file.delete();
        generateMobileStaticHtml();
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {

        return setmealDao.findSetmealCount();
    }

    public void setSetmealAndCheckgroup(Integer setmealId,Integer[] checkgroupIds){
        for (Integer checkgroupId : checkgroupIds) {
            Map<String,Integer> map = new HashMap<>();
            map.put("setmeal_id",setmealId);
            map.put("checkgroup_id",checkgroupId);
            setmealDao.setSetmealCheckgroup(map);
        }
    }
    public void  generateMobileStaticHtml(){
        //准备模板文件中所需的数据
        List<Setmeal> setmealList = this.findAll();
        //生成套餐列表静态页面（掉方法）
        generateMobileSetmealListHtml(setmealList);
        //生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(setmealList);
    }
    //生成静态页面（获取参数，掉生成静态页面方法）
    private void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        HashMap<String, Object> dataMap = new HashMap<>();
        for (Setmeal setmeal : setmealList) {
            Setmeal sm = setmealDao.findById(setmeal.getId());
            dataMap.put("setmeal",sm);
            this.generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html", dataMap);
            this.generateHtml("mobile_orderInfo.ftl","orderInfo_detatil_"+setmeal.getId()+".html",dataMap);
        }
    }
    //生成静态页面（获取参数，掉生成静态页面方法）
    private void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("setmealList", setmealList);
        this.generateHtml("mobile_setmeal.ftl","m_setmeal.html",dataMap);
    }
    //生成静态页面
    private void generateHtml(String templateName, String htmlPageName, Map<String, Object> map) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out =null;
        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            out = new FileWriter(new File(outputpath + "/" + htmlPageName));
            //输出文件
            template.process(map,out);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
